
import {getLoginCode, showToast} from "../../utils/tool";
import {simpleGet, simplePost} from "../../utils/request";

const app = getApp()
const global = app.globalData

Component({
    options:{
        styleIsolation: 'apply-shared'
    },
    properties: {},
    data: {
        user:{},
        hasRegister: false, // 是否已经注册
        showMobileBtn: false, // 获取手机号按钮
        canIUseGetUserProfile: false,
        loading:true,
    },
    lifetimes:{
        attached() {
            // 验证是否注册
            this.checkRegister()

            if (wx.getUserProfile) {
                this.setData({
                    canIUseGetUserProfile: true
                })
            }
        }
    },
    methods: {
        hasRegisterLogin(){
            // 请求登录
            this.requestLogin()
        },

        getUserProfile(e) {
            // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
            wx.getUserProfile({
                desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {

                    const {errMsg, userInfo} = res
                    if(errMsg == 'getUserProfile:ok'){
                        this.setData({
                            user:{
                                avatar: userInfo.avatarUrl,
                                nickname: userInfo.nickName,
                            },
                            showMobileBtn: true
                        })
                    }else {
                        showToast(errMsg)
                    }
                }
            })
        },

        getPhoneNumber(e){
            const {errno, errMsg, code} = e.detail
            if (errMsg == 'getPhoneNumber:ok') {
                simplePost("/login/getPhoneWxMp", {code}).then(r => {
                    // 向用户信息中添加手机号
                    this.setData({
                        [`user.mobile`]: r.mobile,
                    })
                    //登录注册
                    this.requestLogin()

                })
            }
        },
        /***
         * 向后台请求登录
         */
        requestLogin(){
            const {mobile} = this.data.user
            getLoginCode().then(code => {

                simplePost('/login/loginWxMp', {
                    parent_id: global.share_uid || 0,
                    mobile:mobile,
                    code:code,
                }).then(r => {
                    this.triggerEvent('loginSuccess', {
                        token: r.token
                    })
                })
            })

        },
        checkRegister(){    // 检查是否注册过
            getLoginCode().then(code => {
                simplePost('/login/checkRegister', {code:code}).then(r => {
                    this.setData({
                        loading: false,
                        hasRegister: r.isRegister,
                    })
                })
            })
        }

    }
});
